package com.smt.take.ui.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.*
import android.widget.BaseAdapter
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import com.smt.take.R
import com.smt.take.model.beans.CacheSelectedInfo
import com.smt.take.model.beans.GoodsDetailsBean
import com.smt.take.ui.activity.BusinessActivity
import com.smt.take.ui.fragment.GoodsFragment
import com.smt.take.utils.Constants
import com.smt.take.utils.PriceFormater
import com.smt.take.utils.TakeOutApp
import com.squareup.picasso.Picasso
import org.jetbrains.anko.find
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter

class GoodsAdapter(val context: Context?, val goodsFragment: GoodsFragment) : BaseAdapter(),
    StickyListHeadersAdapter {

    companion object {
        const val DURATION: Long = 1000
    }

    var goodsList: MutableList<GoodsDetailsBean> = mutableListOf()

    fun setData(goodsInfoList: MutableList<GoodsDetailsBean>) {
        this.goodsList = goodsInfoList
        notifyDataSetChanged()
    }

    inner class GoodsItemHolder(itemView: View) : View.OnClickListener {
        private val ivIcon: ImageView = itemView.find(R.id.iv_icon)
        private val tvName: TextView = itemView.find(R.id.tv_name)
        private val tvForm: TextView = itemView.find(R.id.tv_form)
        private val tvMonthSale: TextView = itemView.find(R.id.tv_month_sale)
        private val tvNewPrice: TextView = itemView.find(R.id.tv_newprice)
        private val tvOldPrice: TextView = itemView.find(R.id.tv_oldprice)
        private val btnAdd: ImageButton = itemView.find(R.id.ib_add)
        private val btnMinus: ImageButton = itemView.find(R.id.ib_minus)
        private val tvCount: TextView = itemView.find(R.id.tv_count)

        init {
            btnAdd.setOnClickListener(this)
            btnMinus.setOnClickListener(this)
        }

        lateinit var goodsInfo: GoodsDetailsBean

        override fun onClick(v: View?) {
            var isAdd = false
            when (v?.id) {
                R.id.ib_add -> {
                    isAdd = true
                    doAddOperation()
                }
                R.id.ib_minus -> doMinusOperation()
            }
            processRedDotCount(isAdd)
            (goodsFragment.activity as BusinessActivity).updateCartUI()
        }

        // 红点处理
        private fun processRedDotCount(isAdd: Boolean) {
            // 找到此商品属于的类别
            val typeId = goodsInfo.typeId
            // 找到此类别在左侧列表中的位置
            val typePosition = goodsFragment.presenter.getTypePositionByTypeId(typeId)
            // 最后找到tvRedDotCount
            val goodsTypeInfo = goodsFragment.presenter.goodsTypeList[typePosition]
            var redDotCount = goodsTypeInfo.redDotCount
            if (isAdd) {
                redDotCount++
            } else {
                redDotCount--
            }
            goodsTypeInfo.redDotCount = redDotCount
            // 刷新左侧列表
            goodsFragment.goodsTypeAdapter.notifyDataSetChanged()
        }

        // 商品添加
        private fun doAddOperation() {
            // 改变count值
            var count = goodsInfo.count
            if (count == 0) {
                // 第一次点击加号执行动画集
                val showAnimationSet: AnimationSet = getShowAnimation()
                tvCount.startAnimation(showAnimationSet)
                btnMinus.startAnimation(showAnimationSet)
                // 添加缓存
                TakeOutApp.instance.addCacheSelectedInfo(
                    CacheSelectedInfo(
                        goodsInfo.sellerId,
                        goodsInfo.typeId,
                        goodsInfo.id,
                        1
                    )
                )
            } else {
                // 更新缓存
                TakeOutApp.instance.updateCacheSelectedInfo(goodsInfo.id, Constants.ADD)
            }
            count++
            goodsInfo.count = count // 改变数据层
            notifyDataSetChanged()

            // 抛物线
            // 1.克隆+号，并且添加到activity上
            val ib = ImageButton(context)
            // 1.1背景完全相同
            ib.setBackgroundResource(R.drawable.button_add)
            // 1.2位置
            val srcLocation = IntArray(2)
            btnAdd.getLocationInWindow(srcLocation)
            Log.e("location", srcLocation[0].toString() + ":" + srcLocation[1].toString())
            ib.x = srcLocation[0].toFloat()
            ib.y = srcLocation[1].toFloat()
            // 1.3 大小  在activity的绝对位置中去添加执行
            (goodsFragment.activity as BusinessActivity).addImageButton(
                ib,
                btnAdd.width,
                btnAdd.height
            )
            // 2.执行抛物线动画（水平位移，垂直加速位移）
            // 通过activity获取底部位置
            val destLocation = (goodsFragment.activity as BusinessActivity).getCartLocation()
            val parabolaAnim: AnimationSet = getParabolaAnimation(ib, srcLocation, destLocation)
            ib.startAnimation(parabolaAnim)
            // 3.动画完成后回收克隆的+号
        }

        // 抛物线动画
        private fun getParabolaAnimation(
            ib: ImageButton,
            srcLocation: IntArray,
            destLocation: IntArray
        ): AnimationSet {
            val animationSet = AnimationSet(false)
            animationSet.duration = DURATION
            val translateX = TranslateAnimation(
                Animation.ABSOLUTE, 0f,
                Animation.ABSOLUTE, destLocation[0].toFloat() - srcLocation[0].toFloat(),
                Animation.ABSOLUTE, 0f,
                Animation.ABSOLUTE, 0f
            )
            translateX.duration = DURATION
            animationSet.addAnimation(translateX)
            val translateY = TranslateAnimation(
                Animation.ABSOLUTE, 0f,
                Animation.ABSOLUTE, 0f,
                Animation.ABSOLUTE, 0f,
                Animation.ABSOLUTE, destLocation[1].toFloat() - srcLocation[1].toFloat()
            )
            // 加速特效
            translateY.interpolator = AccelerateInterpolator()
            translateY.duration = DURATION
            animationSet.addAnimation(translateY)

            animationSet.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation?) {}

                override fun onAnimationEnd(animation: Animation?) {
                    // 动画结束，获取加号父类view,并且移除
                    val viewParent = ib.parent
                    if (viewParent != null) {
                        kotlin.run {
                            (viewParent as ViewGroup).removeView(ib)
                        }
                    }
                }

                override fun onAnimationRepeat(animation: Animation?) {}

            })
            return animationSet
        }


        // 商品减少
        private fun doMinusOperation() {
            // 改变count值
            var count = goodsInfo.count
            if (count == 1) {
                // 最后一次点击减号执行动画集
                val hideAnimationSet: AnimationSet = getHideAnimation()
                tvCount.startAnimation(hideAnimationSet)
                btnMinus.startAnimation(hideAnimationSet)
                // 删除缓存
                TakeOutApp.instance.deleteCacheSelectedInfo(goodsInfo.id)
            } else {
                // 更新缓存
                TakeOutApp.instance.updateCacheSelectedInfo(goodsInfo.id, Constants.MINUS)
            }
            count--
            goodsInfo.count = count // 改变数据层
            notifyDataSetChanged()
        }

        // 点击加号动画效果
        private fun getShowAnimation(): AnimationSet {
            val animationSet = AnimationSet(false)
            animationSet.duration = DURATION
            // 透视动画
            val alphaAnim: Animation = AlphaAnimation(0.0f, 1.0f)
            alphaAnim.duration = DURATION
            animationSet.addAnimation(alphaAnim)
            // 旋转动画
            val rotateAnim: Animation = RotateAnimation(
                0f,
                720f,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f
            )
            rotateAnim.duration = DURATION
            animationSet.addAnimation(rotateAnim)
            // 平移动画
            val translateAnim: Animation = TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 2f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f
            )
            translateAnim.duration = DURATION
            animationSet.addAnimation(translateAnim)
            return animationSet
        }

        // 点击加号动画效果
        private fun getHideAnimation(): AnimationSet {
            val animationSet = AnimationSet(false)
            animationSet.duration = DURATION
            // 透视动画
            val alphaAnim: Animation = AlphaAnimation(1.0f, 0.0f)
            alphaAnim.duration = DURATION
            animationSet.addAnimation(alphaAnim)
            // 旋转动画
            val rotateAnim: Animation = RotateAnimation(
                720f,
                0f,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f
            )
            rotateAnim.duration = DURATION
            animationSet.addAnimation(rotateAnim)
            // 平移动画
            val translateAnim: Animation = TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 2f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f
            )
            translateAnim.duration = DURATION
            animationSet.addAnimation(translateAnim)
            return animationSet
        }

        @SuppressLint("SetTextI18n")
        fun bindData(goodsInfo: GoodsDetailsBean) {
            this.goodsInfo = goodsInfo
            Picasso.with(context).load(goodsInfo.icon).into(ivIcon)
            tvName.text = goodsInfo.name
            tvName.text = goodsInfo.name
            tvForm.text = goodsInfo.form
            tvMonthSale.text = "月售${goodsInfo.monthSaleNum}份"
            tvNewPrice.text = PriceFormater.format(goodsInfo.newPrice.toFloat())
            tvOldPrice.text = "￥${goodsInfo.oldPrice}"
            tvOldPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            if (goodsInfo.oldPrice > 0) {
                tvOldPrice.visibility = View.VISIBLE
            } else {
                tvOldPrice.visibility = View.GONE
            }
            tvCount.text = goodsInfo.count.toString()
            if (goodsInfo.count > 0) {
                tvCount.visibility = View.VISIBLE
                btnMinus.visibility = View.VISIBLE
            } else {
                tvCount.visibility = View.INVISIBLE
                btnMinus.visibility = View.INVISIBLE
            }
        }

    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val itemView: View
        val goodsItemHolder: GoodsItemHolder
        if (convertView == null) {
            itemView = LayoutInflater.from(context).inflate(R.layout.item_goods, parent, false)
            goodsItemHolder = GoodsItemHolder(itemView)
            itemView.tag = goodsItemHolder
        } else {
            itemView = convertView
            goodsItemHolder = convertView.tag as GoodsItemHolder
        }
        goodsItemHolder.bindData(goodsList[position])
        return itemView
    }

    override fun getCount(): Int {
        return goodsList.size
    }

    override fun getItem(position: Int): Any {
        return goodsList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getHeaderView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val goodsInfo = goodsList[position]
        val typeName = goodsInfo.typeName
        val textView: TextView = LayoutInflater.from(context)
            .inflate(R.layout.item_type_header, parent, false) as TextView
        textView.text = typeName
        textView.setTextColor(Color.BLACK)
        return textView
    }

    override fun getHeaderId(position: Int): Long {
        val goodsInfo = goodsList[position]
        return goodsInfo.typeId.toLong()
    }
}